"""
author: liuxu
date: 2025.2.17
description: 封装sqlite数据库操作，查询hip-prof-PID.db
"""
import sqlite3


class SqliteCtrl:
    _instance = None
    _initialized = False

    def __new__(cls, db_path):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, db_path):
        if not self._initialized:
            self.db_path = db_path
            self.conn = None
            self.cursor = None
            self._initialized = True

    def _connect(self):
        if not self.conn:
            self.conn = sqlite3.connect(self.db_path)
            self.cursor = self.conn.cursor()

    def execute_query(self, query, params=None):
        self._connect()
        try:
            if params:
                self.cursor.execute(query, params)
            else:
                self.cursor.execute(query)
            columns = [col[0] for col in self.cursor.description]
            rows = self.cursor.fetchall()
            result = [dict(zip(columns, row)) for row in rows]
            return result
        except Exception as e:
            print(f"执行查询时出错: {e}")
            return []

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()
            self.conn = None
            self.cursor = None

    def __enter__(self):
        self._connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def get_all_tables_name(self):
        self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
        rows = self.cursor.fetchall()
        tables_name = [r[0] for r in rows]
        return tables_name



if __name__ == '__main__':
    db_pid = 27112
    db_file = r"C:\Users\liuxu\Downloads\hip-prof-27107.db"
    with SqliteCtrl(db_file) as db_obj:
        print(db_obj.get_all_tables_name())

        results=db_obj.execute_query(fr"select * from  HIP_{db_pid}")
        for row in results:
            print(row)

